import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;

import net.roarsoftware.lastfm.*;
import net.roarsoftware.lastfm.Authenticator;

final class LastFm {

  private final String  user;
  private final String  apiKey;
  private final String  secret;
  private       String  token;
  private       Session session;

  LastFm(String user, String apiKey, String secret) {
    this.user = user;
    this.apiKey = apiKey;
    this.secret = secret;
  }

  LastFm(String user) {
    this(user,API_KEY,SECRET);
  }

  LastFm() {
    this("spudtrooper");
  }

  private final static String API_KEY = "52081ce40c29189a5d69341b7b3676ba";
  private final static String SECRET  = "d1da1a1befc76d10e271cf119c8c0fa5";

  public Session login() {
    if (session != null) return session;
    String token = Authenticator.getToken(apiKey);

    String url = "http://www.last.fm/api/auth/?api_key=" + apiKey + "&token=" + token;
    try {
      Browser.displayURL(url);
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    while (true) {
      try {
        Session ses = Authenticator.getSession(token,apiKey,secret);
        if (ses != null) {
          this.session = ses;
          break;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        Thread.sleep(3 * 1000);
      } catch (InterruptedException _) {}
    }
    return session;
  }

  public User getUser() {
    return User.getInfo(session);
  }

  public String getUsername() {
    return user;
  }

  public Collection<Playlist> getPlaylists() {
    return User.getPlaylists(user,apiKey);
  }

  public Result addTrack(Playlist playlist, String artist, String track) {
    return addTrack(playlist.getId(),artist,track);
  }

  public Result addTrack(int playlistId, String artist, String track) {
    login();
    return Playlist.addTrack(playlistId,artist,track,session);
  }

  public static void main(String[] args) {
    LastFm l = new LastFm();
    l.login();
    Playlist playlist = null;
    for (Playlist pl : l.getPlaylists()) {
      playlist = pl;
      break;
    }
    System.out.println(playlist.getTitle());
    for (Track t : playlist.getTracks()) {
      System.out.println(" - " + t.getArtist() + ":" + t.getLocation());
    }
  }
}
